import { loginByPhone, fetchTokens } from '@/api/auth'
import { getUserRoles, getUserInfo } from '@/api/user'
import { getToken, removeToken, getTeam, removeTeam, getUser, removeUser } from '@/utils/auth'

const user = {
  state: {
    login: getToken(),
    userId: getUser(),
    accessToken: '',
    refreshToken: '',
    name: '',
    avatar: '',
    team: getTeam() || null, // null 是未知到底加入团队没有，''是真的还没有加入团队
    roles: []
  },

  mutations: {
    SET_LOGIN: (state, login) => {
      state.login = login
    },
    SET_USER: (state, userId) => {
      state.userId = userId
    },
    SET_ACCESS_TOKEN: (state, accessToken) => {
      state.accessToken = accessToken
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_TEAM: (state, team) => {
      state.team = team
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    LOG_OUT(state) {
      state.userId = ''
      state.roles = []
      state.login = 0
      // state.accessToken = ''
      // state.refreshToken = ''
      state.team = null
    }
  },

  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByPhone(userInfo).then(response => {
          if (response.status === 204) {
            reject(new Error('手机或密码错误，登录失败'))
          } else if (response.status === 200) {
            fetchTokens(response.data.code).then(res => {
              if (res.status === 200 && res.data.tokenType === 'Bearer') {
                commit('SET_USER', res.data.userId)
                // commit('SET_ACCESS_TOKEN', res.data.accessToken)
                // commit('SET_REFRESH_TOKEN', res.data.refreshToken)
                resolve()
              } else reject(new Error(`failed to get tokens`))
            })
          }
        }).catch(error => {
          console.log(error.message)
          reject(error)
        })
      })
    },

    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.userId).then(response => {
          commit('SET_AVATAR', response.data.avatar)
          commit('SET_NAME', response.data.username)
          commit('SET_TEAM', response.data.team)
          resolve(response.data)
        }).catch(err => {
          reject(err)
        })
      })
    },

    GetUserRoles({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserRoles(state.userId).then(response => {
          if (response.status === 200) {
            commit('SET_ROLES', response.data.roles)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('LOG_OUT')
        removeToken()
        removeTeam()
        removeUser()
        resolve()
      })
    }

  }
}

export default user
